<template>
  <div>
    <div class="bg_fff p_14 pb_0 mb_12">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
        <el-form-item label="" prop="keyword">
          <el-input
            style="width: 180px"
            v-model="queryParams.keyword"
            placeholder="请输入类型名称/ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="优惠活动" prop="task_id">
          <el-select
            style="width: 160px"
            v-model="queryParams.task_id"
            placeholder="请选择优惠活动"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="dict in taskList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="times">
          <el-date-picker
            v-model="times"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleQuery"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建人" prop="admin">
          <el-select filterable
                     style="width: 160px"
                     v-model="queryParams.admin"
                     placeholder="请选择创建人"
                     clearable
                     @change="handleQuery"
          >
            <el-option
              v-for="dict in adminList"
              :key="dict.id"
              :label="dict.user_login"
              :value="dict.user_login"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="当前状态" prop="status">
          <el-select
            style="width: 160px"
            v-model="queryParams.status"
            placeholder="请选择当前状态"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="dict in statusList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
          >搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="bg_fff boxflex">
      <div
        class="flexrowbetween flexwrapper mb_15"
        style="align-items: flex-start"
      >
        <div class="flex">
          <el-button
            plain
            type="primary"
            class="bg_fff mr_5 f-14 c_primary"
            size="mini"
            @click="selectAll"
          >全选
          </el-button
          >
          <el-button
            plain
            type="primary"
            class="bg_fff f-14 c_primary"
            size="mini"
            @click="selectInvert"
          >反选
          </el-button
          >
          <el-button
            type="primary"
            class="f-14"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['favorable:add']"
          >新增
          </el-button
          >
        </div>
        <div>
          <el-button type="danger" :disabled='multiple' size="mini" class="f-14 mr_10" @click="handleStopAll"  v-hasPermi="['favorable:batchStop']">批量暂停</el-button>
           <el-button type="primary"  size="mini" class="f-14 mr_10" @click="handleExport" v-hasPermi="['favorable:export']">导出</el-button>
          <el-dropdown trigger="click" class="mr_10"  v-hasPermi="['favorable:customList']">
            <el-button type="primary" size="mini" class="f-14">
              自定义列表
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <div class="dropbody">
                <el-checkbox-group v-model="checkedOption" class="flexcolumn" @change="changeSelect">
                  <el-checkbox v-for="(item,index) in selectoptions" :label="item.label" :key="index" class="m_5">{{item.label}}</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-button
            plain
            type="primary"
            size="mini"
            class="bg_fff f-14 c_primary"
            @click="handleAdd"
            >导出</el-button
          > -->
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        ref="tablelayout"
        class="commtable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" type="index" align="center" v-if="comboOption.includes('序号')">
          <template slot-scope="scope">
            <span>{{ (queryParams.page - 1) * queryParams.num + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态开关" prop="id" width="160" v-if="comboOption.includes('状态开关')">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus($event,scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column v-if="comboOption.includes('类型ID')"
                         align="center"
                         label="类型ID"
                         prop="id"
                         :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column v-if="comboOption.includes('类型名称')"
                         align="center"
                         label="类型名称"
                         prop="name"
                         min-width="150"
                         :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column v-if="comboOption.includes('优惠活动绑定')"
                         align="center"
                         label="优惠活动绑定"
                         prop="mobile"
                         min-width="200"
                         :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.task.length">
              <span v-for="(item, index) in scope.row.task" :key="index">{{
                item.name
                }}<span v-if="index<scope.row.task.length-1">,</span></span>
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>
        <el-table-column v-if="comboOption.includes('创建时间')"
                         align="center"
                         label="创建时间"
                         prop="create_time"
                         min-width="150"
                         :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.create_time || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="comboOption.includes('创建人')"
                         align="center"
                         label="创建人"
                         prop="name"
                         min-width="100"
                         :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.admin">{{
              scope.row.admin.user_login || '-'
            }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" v-if="comboOption.includes('状态')" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span v-if="scope.row.status==1" class="succdot mr_5"></span>
            <span v-else class="dangerdot mr_5"></span>
            <span>{{ scope.row.status_name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="操作"
          width="160"
          fixed="right"
          align="center"
        >
          <template slot-scope="scope">
            <div class="flexcenter btnflex">
              <div class="commhover mr_10" @click="handleUpdate(scope.row)">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="编辑"
                  placement="top-start"
                >
                  <i class="el-icon-edit-outline f-24 c_primary"></i>
                </el-tooltip>
              </div>
              <!-- <div class="commhover mr_10" @click="handleDelete(scope.row)">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top-start"
                >
                  <i class="el-icon-delete c_F11616 f-24"></i>
                </el-tooltip>
              </div> -->
              <div
                class="commhover"
                @click="changeStatus(0,scope.row)"
                v-if="scope.row.status == 1"
              >
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="暂停"
                  placement="top-start"
                >
                  <svg-icon class-name="f-24 " icon-class="pause"/>
                </el-tooltip>
              </div>

              <div
                class="commhover"
                @click="changeStatus(1,scope.row)"
                v-if="scope.row.status == 0"
              >
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="启用"
                  placement="top-start"
                >
                  <svg-icon class-name="f-24 c_12A000" icon-class="start1"/>
                </el-tooltip>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.num"
        @pagination="getList"
      />
    </div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="620px"
      class="commdia"
      :before-close="handleClose"
      :close-on-click-modal='false'
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="套餐类型名称：" prop="name">
          <el-input v-model="form.name" placeholder="请输入套餐类型名称"/>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">暂停</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading='subloading' @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import {
    getUserList,
    packageIndex,
    createPackage,
    statusPackageCloseAll,
    deletePackage,
    statusPackageOpen,
    statusPackageClose,
    editPackage,
    reqPackageIndexExport,

  } from '@/api/favorable'
  import { reqTrendDayChartExport, reqTrendHourChartExport, reqTrendMonthChartExport } from '@/api/income'

  export default {
    data() {
      return {
        queryParams: {
          page: 1,
          num: 10,
          admin: '',
          keyword: '',
          status: '',
          task_id: ''
        },
        times: '',
        adminList: [],
        taskList: [],
        statusList: [
          { name: '开启', id: 1 },
          { name: '暂停', id: 0 }
        ],
        loading: false,
        tableData: [],
        total: 0,
        checkedOption: [],
        selectoptions: [
          { id: 1, label: '序号' },
          { id: 2, label: '状态开关' },
          { id: 3, label: '类型ID' },
          { id: 5, label: '类型名称' },
          { id: 6, label: '优惠活动绑定' },
          { id: 7, label: '创建时间' },
          { id: 8, label: '创建人' },
          { id: 9, label: '状态' }
        ],
        exportColumns: [
          {key: 'id', label: `类型ID`,},
          {key: 'name', label: `类型名称`},
          {key: 'task_name', label: `优惠活动绑定`,},
          {key: 'create_time', label: `创建时间`},
          {key: 'admin.user_login', label: `创建人`,},
          {key: 'status_name', label: `状态`,},
        ],
        paramsForm:{},
        rowids: [],
        multiple: true,
        form: {},
        rules: {
          name: [{ required: true, message: '请输入套餐类型名称', trigger: 'blur' }]
        },
        open: false,
        title: '',
        subloading: false,
      }
    },
    created() {
      let comboOption = JSON.parse(localStorage.getItem('comboOption'))
      if (comboOption) {
        this.changeSelect(comboOption)
      }
      this.checkedOption = this.comboOption

      this.getDicts('/manager/api/getPackageTaskList').then(res => {
        this.taskList = res.data
      })
      this.getUserList()
      this.getList()
    },
    computed: {
      ...mapState({
        comboOption: (state) => state.paramsoption.comboOption
      })
    },
    methods: {
      getUserList() {
        getUserList().then(res => {
          this.adminList = res.data
        })
      },
      getList() {
        this.loading = true
        let params = {
          page: this.queryParams.page,
          num: this.queryParams.num
        }
        if (this.queryParams.keyword) {
          params.keyword = this.queryParams.keyword
        }
        if (this.queryParams.status || this.queryParams.status === 0) {
          params.status = this.queryParams.status
        }
        if (this.queryParams.admin) {
          params.admin = this.queryParams.admin
        }
        if (this.queryParams.task_id) {
          params.task_id = this.queryParams.task_id
        }
        if (this.times && this.times.length) {
          params.start = this.times[0]
          params.end = this.times[1]
        }
        this.paramsForm=params;
        packageIndex(params).then((response) => {
          this.tableData = response.data.list
          console.log('55555', this.tableData)
          this.total = response.data.count
          this.loading = false
        })
        this.loading = false
      },

      handleQuery() {
        this.queryParams.page = 1
        this.getList()
      },

      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },

      changeSelect(arr) {
        this.$store.commit('SET_COMBOOPTION', arr)
        this.$nextTick(() => {
          //在数据加载完，重新渲染表格
          this.$refs.tablelayout && this.$refs.tablelayout.doLayout()
        })
      },

      handleSelectionChange(selection) {
        this.rowids = selection.map((item) => item.id)
        this.multiple = !selection.length
      },

      selectAll() {
        //全选功能,先进行清除状态，然后再选择是全选还是多选
        this.$refs.tablelayout.clearSelection()
        this.tableData.forEach((row) => {
          this.$refs.tablelayout.toggleRowSelection(row)
        })
      },

      selectInvert() {
        //反选
        let listfiter = this.tableData.filter(item => {
          return this.rowids.indexOf(item.id) == -1// 不包含选中的
        })
        this.$refs.tablelayout.clearSelection()
        if (listfiter && listfiter.length > 0) {
          listfiter.forEach((item) => {
            this.$refs.tablelayout.toggleRowSelection(item)
          })
        }
      },

      handleDelete(row) {
        this.$modal.confirm('确定删除该条套餐类型？').then(() => {
          return deletePackage({
            id: row.id
          })
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {
        })
      },

      handleDeleteAll() {
        this.$modal.confirm('确定删除选中的套餐类型？').then(() => {
          return deletePackageAll({
            id: this.rowids
          })
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {
        })
      },

      handleStopAll() {
        this.$modal.confirm('确定暂停选中的套餐类型？').then(() => {
          return statusPackageCloseAll({
            id: this.rowids
          })
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess('暂停成功')
        }).catch(() => {
        })
      },

      changeStatus(val, row) {
        if (val) {
          this.$modal.confirm('是否开启该条类型').then(function() {
            return statusPackageOpen({
              id: row.id
            })
          }).then(() => {
            this.getList()
            this.$modal.msgSuccess('开启成功')
          }).catch(() => {
            console.log('-------')
            row.status = 0
          })
        } else {
          this.$modal.confirm('是否暂停该条类型').then(function() {
            return statusPackageClose({
              id: row.id
            })
          }).then(() => {
            this.getList()
            this.$modal.msgSuccess('暂停成功')
          }).catch(() => {
            console.log('-1111111------')
            row.status = 1
          })
        }

      },

      reset() {
        this.form = {
          id: undefined,
          name: '',
          status: 1
        }
      },

      handleAdd() {
        this.reset()
        this.title = '新增'
        this.open = true
      },

      handleUpdate(row) {
        this.reset()
        this.title = '编辑'
        this.form.id = row.id
        this.form.name = row.name
        this.form.status = row.status
        this.open = true
      },

      handleClose() {
        this.open = false
      },

      handleSubmit() {
        this.$refs.form.validate(valid => {
          if (!valid) return
          this.subloading = true
          if (this.form.id) {
            editPackage(this.form).then(() => {
              this.handleClose()
              this.$message.success('编辑成功')
              this.subloading = false
              this.getList()
            }).catch(() => {
              this.subloading = false
            })
          } else {
            createPackage(this.form).then(() => {
              this.handleClose()
              this.$message.success('新增成功')
              this.subloading = false
              this.getList()
            }).catch(() => {
              this.subloading = false
            })
          }
        })
      },
      handleExport() {

        let form = JSON.parse(JSON.stringify(this.paramsForm))
        let head = []
        let keys = []
        this.exportColumns.forEach(item => {
          this.checkedOption.forEach(sitem => {
            if (sitem == item.label) {
              if (head.indexOf(item.label) == -1) {
                head.push(item.label)
              }
              if (keys.indexOf(item.key) == -1) {
                keys.push(item.key)
              }
            }
          })
        })
        form.head = head
        form.keys = keys
        delete form.page
        delete form.num
        reqPackageIndexExport(form).then((res) => {
          console.log('333', res)
          if (res.code == 1) {
            const a = document.createElement('a')
            document.body.appendChild(a)
            a.download = '套餐列表数据.xls'
            a.href = res.data
            a.click()
            document.body.removeChild(a)
          }

        })

      }
    }
  }
</script>

<style lang="scss" scoped>
  .incomebox {
    width: 100%;
    height: 95px;
    padding: 0 30px;
    background: url("~@/assets/images/fin_bg.png") 100% 100% no-repeat;
    background-size: cover;
  }

  .l_img {
    width: 62px;
    height: 55px;
  }

  .boxflex {
    padding: 16px 20px;

    .line {
      width: 2px;
      height: 18px;
      background-color: #1670f1;
    }
  }
</style>
